// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.properties.controllers;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.core.DenguesCorePlugin;
import org.dengues.core.components.ENodeParameterName;
import org.dengues.core.components.NodePropertyParameter;
import org.dengues.core.connectivity.IConnectivityManager;
import org.dengues.core.metadata.MetadataHelper;
import org.dengues.core.metadata.MetadataUtils;
import org.dengues.designer.ui.process.models.CompNode;
import org.dengues.designer.ui.properties.PropertyTabDynamicSection;
import org.dengues.designer.ui.properties.cmd.PropertyChangeTextCommand;
import org.dengues.model.DenguesModelManager;
import org.dengues.model.database.DBTable;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.model.database.DiagramChild;
import org.dengues.model.project.ConnPropertyAttriType;
import org.dengues.model.project.ConnPropertySetType;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ListDialog;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-5-11 qiang.zhang $
 * 
 */
public class DBTablePropertyControler extends AbstractPropertyController {

    /**
     * Qiang.Zhang.Adolf@gmail.com DBTableControler constructor comment.
     * 
     * @param dps
     */
    public DBTablePropertyControler(PropertyTabDynamicSection dps) {
        super(dps);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.dengues.designer.ui.properties.controllers.AbstractPropertyController#createControl(org.eclipse.swt.widgets.Composite,
     * org.dengues.core.components.NodePropertyParameter, org.eclipse.swt.widgets.Control)
     */
    @Override
    public Control createControl(final Composite composite, final NodePropertyParameter param, Control lastControl) {
        Composite subcomposite = new Composite(composite, SWT.NONE);
        GridLayout gridLayout = new GridLayout(3, false);
        gridLayout.marginBottom = 0;
        gridLayout.marginHeight = 0;
        gridLayout.marginLeft = 0;
        gridLayout.marginRight = 0;
        gridLayout.marginTop = 0;
        gridLayout.marginWidth = 0;
        subcomposite.setLayout(gridLayout);
        subcomposite.setLayoutData(new GridData(GridData.FILL_BOTH));
        subcomposite.setBackground(composite.getBackground());
        CLabel cLabel = getWidgetFactory().createCLabel(subcomposite, param.getDisplayName());
        GridData gridData = new GridData();
        gridData.widthHint = STANDARD_LABEL;
        cLabel.setLayoutData(gridData);
        Text text = null;
        text = getWidgetFactory().createText(subcomposite, "", SWT.BORDER); //$NON-NLS-1$
        ControlDecoration controlDecoration = new ControlDecoration(text, SWT.RIGHT | SWT.TOP);
        if (param.isRequired()) {
            FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
                    FieldDecorationRegistry.DEC_REQUIRED);
            controlDecoration.setImage(fieldDecoration.getImage());
            controlDecoration.setDescriptionText(fieldDecoration.getDescription());
        }
        final Text labelText = (Text) controlDecoration.getControl();
        register(param, labelText);
        if (param.getValue() != null) {
            labelText.setText(param.getValue().toString());
        }
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.heightHint = SWT.DEFAULT;

        data.horizontalIndent = FieldDecorationRegistry.getDefault().getMaximumDecorationWidth();
        labelText.setLayoutData(data);
        labelText.setData(PARAMETER_NAME, param.getName());
        labelText.setEditable(!param.isReadOnly());
        labelText.setBackground(param.isReadOnly() ? Display.getDefault().getSystemColor(SWT.COLOR_GRAY) : subcomposite
                .getBackground());
        curControlMap.put(param.getName(), labelText);
        Button btn = getWidgetFactory().createButton(subcomposite, "...", SWT.PUSH);
        btn.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                if (dps.getElem() instanceof CompNode) {
                    Job job = new Job("Open Database Table Selector Dialog") {

                        @Override
                        protected IStatus run(final IProgressMonitor monitor) {
                            monitor.beginTask("Waiting for opening Database Table Selector Dialog...", IProgressMonitor.UNKNOWN);
                            CompNode compNode = (CompNode) dps.getElem();
                            NodePropertyParameter connPara = compNode.getElementParameter(ENodeParameterName.CONNECTIVITY
                                    .getName());
                            Object value = connPara.getValue();
                            ConnPropertySetType setType = MetadataHelper.getConnSetType(value.toString());
                            EList<ConnPropertyAttriType> attributes = setType.getAttributes();
                            Properties props = new Properties();
                            for (ConnPropertyAttriType attri : attributes) {
                                props.put(attri.getName(), attri.getValue());
                            }
                            IConnectivityManager cM = DenguesCorePlugin.getDefault().getDenguesUiService()
                                    .getConnectivityManager();
                            cM.getConnection(props, true, false);
                            if (!monitor.isCanceled()) {
                                if (cM.getConnection() != null) {
                                    DatabaseDiagram cdb = DenguesModelManager.getDatabaseFactory().createDatabaseDiagram();
                                    MetadataUtils.getDbTables(cdb, cM.getConnection(), monitor);
                                    EList<DiagramChild> dbChildren = cdb.getDbChildren();
                                    final List<String> tableNames = new ArrayList<String>();
                                    for (DiagramChild dc : dbChildren) {
                                        if (dc instanceof DBTable) {
                                            tableNames.add(((DBTable) dc).getName());
                                        }
                                    }
                                    Display.getDefault().asyncExec(new Runnable() {

                                        /*
                                         * (non-Javadoc)
                                         * 
                                         * @see java.lang.Runnable#run()
                                         */
                                        public void run() {
                                            ListDialog dialog = new ListDialog(composite.getShell());
                                            dialog.setContentProvider(cprovider);
                                            dialog.setLabelProvider(lProvider);
                                            dialog.setInput(tableNames);
                                            if (dialog.open() == ListDialog.OK) {
                                                Object[] result2 = dialog.getResult();
                                                if (result2.length > 0) {
                                                    PropertyChangeTextCommand command = new PropertyChangeTextCommand(dps
                                                            .getElem(), param.getName(), result2[0].toString());
                                                    getCommandStack().execute(command);
                                                    labelText.setText(result2[0].toString());
                                                }
                                            }
                                        }
                                    });

                                }
                            } else {
                                return Status.CANCEL_STATUS;
                            }
                            monitor.done();
                            return Status.OK_STATUS;
                        }
                    };
                    job.setUser(true);
                    job.schedule();
                }
            }

        });
        return btn;
    }

    private IStructuredContentProvider cprovider = new IStructuredContentProvider() {

        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof List) {
                return ((List) inputElement).toArray(new Object[0]);
            }
            return new Object[0];
        }

        public void dispose() {

        }

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

        }

    };

    private LabelProvider lProvider = new LabelProvider() {

        /*
         * (non-Javadoc)
         * 
         * @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
         */
        @Override
        public Image getImage(Object element) {
            return ImageUtil.getImage(IDenguesSharedImage.VIEW_TABLE);
        }

    };
}
